import { Injectable  } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import {RequestReplyService} from '../services/request-reply.service'

import {Reply} from '../entity/Reply';
import {User, BookedWrapper, Booked} from '../entity/TT';
import { EventService , EventSource} from './event.service';
import { NGXLogger } from 'ngx-logger';

@Injectable({
  providedIn: 'root'
})
export class BookedService  {

  bookedWrapper: BookedWrapper = null;

  reloading: boolean = false;

  TimeSlice : number = 1000;

  constructor(
    private log: NGXLogger,
    private requestService: RequestReplyService,
    private eventService: EventService ) {


     }


  refresh(){
    this.log.debug("refresh...")
    this.requestService.GetCurrentBookedList()
    .subscribe((bookeds: BookedWrapper) => {
      if(bookeds){
          this.bookedWrapper = bookeds;
          this.startTimer(this.bookedWrapper);
          this.eventService.sendEvent(EventSource.BOOKED, this.bookedWrapper);
      }
    });
  }

  startTimer(bm: BookedWrapper){
    if(!bm){
      return;
    }

    let delay = bm.delay;
    if(!(delay && delay >= 0)){
      return;
    }

    this.log.debug("startTimer...", delay)
    this.eventService.subscribeClockTick((ticks:number)=>{
      if(this.bookedWrapper.delay <= 0){
        this.timesUp();
      }else{
        this.bookedWrapper.delay -= this.TimeSlice;
      }
    });
  }

  timesUp(){
    if(this.reloading)
      return;

    this.reloading = true;

    if(this.bookedWrapper.current){
      let booked : Booked = this.bookedWrapper.current;
      this.requestService.ExitBooked(booked).subscribe((result: any) => {
         this.log.debug("ExitBooked=>", result)
         this.reload();
      });
    }else{
      this.reload();
    }

  }

  reload(){
    this.log.debug("reload /workbench")
    location.href='/workbench'
  }

}





